<template>
  <!-- 告警处理 -->
  <!-- <BaseMainSlot :show-tab="false" :showBtnBox="false">
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
<div class="search-btn search-btns" @click.stop="search()">
  <i class="el-icon-circle-check"></i>
  <p>查询</p>
</div>
<div class="select-box-content">
  <div class="select-box-content-name">鱼塘名称</div>
  <el-select filterable clearable v-model="fishPondId">
    <el-option v-for="item in fishPondArr" :key="item.fishPondId" :label="item.pondName" :value="item.fishPondId" />
  </el-select>
</div>
<div class="select-box-content">
  <div class="select-box-content-name">数据类型</div>
  <el-select filterable clearable v-model="dataTypeId">
    <el-option v-for="(item, index) in dataTypeList" :key="index" :value="item.dataTypeId" :label="item.dataTypeName" />
  </el-select>
</div>
<div class="select-box-content">
  <div class="select-box-content-name">数据项</div>
  <el-select filterable clearable v-model="dataItemId">
    <el-option v-for="(item, index) in dataitemlist" :key="index" :value="item.iotDataItemId"
      :label="item.dataItemName" />
  </el-select>
</div>
<div class="select-box-content">
  <div class="select-box-content-name">告警日期</div>
  <el-date-picker v-model="buildDateTime" type="daterange" range-separator="至" start-placeholder="开始日期"
    end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable />
</div>
</el-collapse-item>
</el-collapse>
</template>
<template v-slot:tab-select></template>
<template v-slot:table-box>
      <el-table v-show="nowselecttype === 0" v-loading="false" :data="tableData" stripe border height="88%"
        @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column v-for="item, index in formDatalists" :key="index" :type="`${item.porp}`" :prop="`${item.porp}`"
          :label="item.name" :min-width="'130'" :column-key="`${item.porp}`">
          <template v-if="scope.row[`${item.porp}`] !== undefined" slot-scope="scope">
            <span v-if="item.type !== 'TimePicker'">{{ scope.row[`${item.porpName}`] || scope.row[`${item.porp}`] ||
    '——'
              }}</span>
            <span v-else-if="item.linkage === 'breedingFlag'">{{ scope.row[`${item.porpName}`] ? '是' : '否' || '——'
              }}</span>
            <span v-else>{{ scope.row[`${item.porp}`] ? scope.row[`${item.porp}`] : '——' }}</span>
          </template>
</el-table-column>
<el-table-column label="操作" width="100">
  <template slot-scope="scope">
            <el-button type="warning" v-if="scope.row.fishPondId && judgePermission(18, 'handle')" plain size="small"
              :disabled="scope.row.disposeStatus" @click="handlingmmessage(scope.row)">处理</el-button>
          </template>
</el-table-column>
</el-table>
<Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize"
  @changeCurrentPage="changeCurrentPage" />
</template>
<template v-slot:dialog>
      <el-dialog title="处理结果" :visible.sync="dialogVisible" width="30%">
        <div class="zhdialog">
          <el-form :model="formData" :rules="rules" ref="formData">
            <el-form-item label prop="disposeContent" class="w100p">
              <el-input v-model="formData.disposeContent" type="textarea" :rows="4" placeholder="请输入处理意见" />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="dialogVisible = false">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="clickqueren('formData')">确 定</el-button>
        </span>
      </el-dialog>
    </template>
</BaseMainSlot> -->


  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag"
        @search="searchFormData" @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <!-- <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot> -->
    </template>
    <template v-slot:table>
      <el-table v-show="nowselecttype === 0" v-loading="false" :data="tableData" stripe border height="100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column v-for="item, index in formDatalists" :key="index" :type="`${item.porp}`" :prop="`${item.porp}`"
          :label="item.name" :column-key="`${item.porp}`" :min-width="item.width || 120">
          <template v-if="scope.row[`${item.porp}`] !== undefined" slot-scope="scope">
            <span v-if="item.type !== 'TimePicker'">{{ scope.row[`${item.porpName}`] || scope.row[`${item.porp}`] ||
        '——'
              }}</span>
            <span v-else-if="item.linkage === 'breedingFlag'">{{ scope.row[`${item.porpName}`] ? '是' : '否' || '——'
              }}</span>
            <span v-else>{{ scope.row[`${item.porp}`] ? scope.row[`${item.porp}`] : '——' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <!--
            -->
            <el-button type="warning" v-if="scope.row.fishPondId && judgePermission(18, 'handle')" plain size="small"
              :disabled="scope.row.disposeStatus" @click="handlingmmessage(scope.row)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog title="处理结果" :visible.sync="dialogVisible" width="30%">
        <div class="zhdialog">
          <el-form :model="formData" :rules="rules" ref="formData">
            <el-form-item label prop="disposeContent" class="w100p">
              <el-input v-model="formData.disposeContent" type="textarea" :rows="4" placeholder="请输入处理意见" />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="dialogVisible = false">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="clickqueren('formData')">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';

import fishPondApi from "@/api/basic-info-manage/fishPond";
import dataItemApi from "@/api/basic-info-manage/data-item-manage/index";
import dataTypeApi from "@/api/basic-info-manage/data-type-manage";
import nowpagereq from "@/api/monitoring-alarm/historical-alarm-record/index";
import { mymixin } from "@/utils/mixins";
import SearchBox from "@/components/SearchBox";

import { mapGetters } from "vuex";
export default {
  name: "AlarmHandling",
  components: {
    Pagination,
    MainSlot,
    SearchForm,
    SearchBox,
  },
  mixins: [mymixin],
  data() {
    return {
      unfoldFlag: false,
      rules: {
        disposeContent: [
          { required: true, message: "处理意见不能为空", trigger: "blur" }
        ]
      },
      // 可选择数据类型
      dataTypeList: [],
      // 可选择批次
      batchList: [],
      echartlist: {
        xAxisdata: [],
        xData: ["前后一小时数据"],
        seriesData: []
      },
      nowwarringmessage: {},
      // -----------
      defaulthandinglist: ["已处理完成", "未处理", "其他"],
      defaulthandindex: 0,
      dialogVisible: false,
      nowselecttype: 0, // 0为物联自动告警 2为手动记录告警 1为数值告警
      dataitemlist: [],
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      // 可选择所有地块
      alarmTypeList: [],
      // 鱼塘
      fishPondArr: [],
      // 查询 start
      batchNo: "",
      alarmTypeId: "",
      dataTypeId: "",
      dataItemId: "",
      buildDateTime: "",
      disposeTime: "",
      fishPondId: "",
      dataTypeId: "",
      dataItemId: "",
      // 查询 end
      editObject: {},
      showAddEditDialog: false,
      btnList: ['add', 'delete'],
      formItemList: [
        {
          label: '鱼塘名称',
          type: 'select',
          selectOptions: [],
          param: 'fishPondId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '数据类型',
          type: 'select',
          selectOptions: [],
          param: 'dataTypeId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '数据项',
          type: 'select',
          selectOptions: [],
          param: 'dataItemId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '发生日期',
          type: 'datetimerange',
          param: 'dateTime',
          multiple: false,
          isShow: true
        },
      ],
      searchFormDataItem: {},
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "fishPondName",
          typeObj: {},
          name: "鱼塘名称",
          required: true,
          width: '100'
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "messageInfo",
          typeObj: {},
          name: "告警信息",
          width: '400'
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "dataItemName",
          porpName: "buildingName",
          linkage: true,
          typeObj: {},
          name: "告警数据项",
          width: '200'
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "alarmPresetValue",
          porpName: "columnName",
          typeObj: {},
          name: "预设告警值"
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "actualAlarmValue",
          typeObj: {},
          name: "实际告警值"
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          porp: "happenTime",
          typeObj: {},
          name: "发生时间",
          width: '150'
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "dataTypeName",
          typeObj: {
            // list: [
            //   { name: "是", value: "是" },
            //   { name: "否", value: "否" }
            // ],
            // listName: ["name", "value"]
          },
          name: "告警数据类型"
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "staffNameList",
          typeObj: {},
          name: "告警联系人"
        },
        // {
        //   type: "Status", // input Select Checkbox TimePicker
        //   porp: "disposeStatus",
        //   typeObj: {},
        //   name: "告警信息状态"
        // },
        // {
        //   type: "TimePicker", // input Select Checkbox TimePicker
        //   porp: "disposeTime",
        //   typeObj: {},
        //   name: "处理时间"
        // }
      ]
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    this.routerParams = this.$route.query ? this.$route.query : {}
    this.fishPondId = this.routerParams.fishPondId ? this.routerParams.fishPondId : undefined
    this.search();
  },
  mounted() {
    this.getselecltlist();
  },
  methods: {
    searchFormData(data) {
      this.currentPage = 1;
      let endData = null;
      let startData = null;
      if (data.dateTime && data.dateTime.length == 2) {
        startData = data.dateTime[0] + ' 00:00:00';
        endData = data.dateTime[1] + ' 23:59:59';
      }
      this.searchFormDataItem = {
        ...this.searchFormDataItem,
        ...data,
        startTime: startData,
        endTime: endData
      };
      this.search();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('fishPondId') !== -1) {
          let selectOptions = this.fishPondArr.map(data => {
            return {
              text: data.pondName, value: data.fishPondId
            }
          })
          item.defaultSelect = this.searchFormDataItem[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('dataTypeId') !== -1) {
          let selectOptions = this.dataTypeList.map(data => {
            return {
              text: data.dataTypeName, value: data.dataTypeId
            }
          })
          item.defaultSelect = this.searchFormDataItem[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('dataItemId') !== -1) {
          let selectOptions = this.dataitemlist.map(data => {
            return {
              text: data.dataItemName, value: data.iotDataItemId
            }
          })
          item.defaultSelect = this.searchFormDataItem[item.param];
          item.selectOptions = selectOptions;
        };

      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    // 获取当前拥有类型表格
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchFormDataItem,
          disposeStatus: false
        }
      };
      nowpagereq.queryPageList(params, false).then(res => {
        this.loading = false;
        if (!res.success) {
          this.$message.error(res.message || "当前告警历史表格获取失败");
        }
        res.data.content.forEach(item => {
          item.staffNameList = item.staffNameList.join(',')
        })
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.routerParams = {}
      });
    },
    // 表格中的标签
    filterTag(value, row) {
      return row.disposeStatus === value;
    },
    // 处理意见
    handlingmmessage(e) {
      this.formData = {};
      this.dialogVisible = true;
      this.formData.alarmMessageId = e.alarmMessageId;
    },
    // 点击弹框确认
    clickqueren(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          nowpagereq.editlist({ ...this.formData, disposeStatus: true }).then(res => {
            if (res.success) {
              this.search();
              this.$message.success("处理成功");
              this.dialogVisible = false;
            } else {
              this.$message.error(res.message || "处理失败");
            }
          });
        } else {
          return false;
        }
      });
    },
    // 获取下拉选择数据
    async getselecltlist() {
      // 获取鱼塘
      const { data: fishPondArr } = await fishPondApi.queryByCondition({});
      const { data: dataTypeList } = await dataTypeApi.queryExistence({});
      const { data: dataitemlist } = await dataItemApi.queryByCondition({})
      this.fishPondArr = fishPondArr || [];
      this.dataTypeList = dataTypeList || [];
      this.dataitemlist = dataitemlist || [];
      this.dataitemlist = this.dataitemlist.filter(item => {
        return item.dataType && item.dataType.mainingControlType == 'COLLECTION' && item.iotDataItemId
      })
      console.log(dataitemlist, '---')
      this.setFormOptions();
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.ownUnitId;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0)
        this.delActive = true;
      else this.delActive = false;
    }
  }
};
</script>
<style lang="scss" scoped></style>
